<!--
 * @Author: your name
 * @Date: 2020-12-27 12:48:22
 * @LastEditTime: 2021-03-28 10:27:18
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \white-jotter-blog-vue\src\components\content\ImgUpload.vue
-->
<template>
  <el-upload
    class="img-upload"
    ref="uploadRef"
    :action=uploadUrl
    multiple
    :headers="headers"
    list-type="picture-card"
    :limit="1"
    :file-list="fileList"
    :on-preview="handlePreview"
    :on-remove="handleRemove"
    :before-remove="beforeRemove"
    :on-success="handleSuccess"
    :on-exceed="handleExceed"
    :before-upload="beforeAvatarUpload"
  >
    <i class="el-icon-upload"></i>
    <div
      slot="tip"
      class="el-upload__tip"
    >只能上传jpg/png文件，且不超过2M</div>
  </el-upload>
</template>

<script>
export default {
  name: "ImgUpload",
  data() {
    return {
      fileList: [],
      url: "",
      headers: {
        Authorization: window.localStorage.getItem("token"),
      },
    };
  },
  computed:{
    uploadUrl(){
      return process.env.VUE_APP_BASE_URL + "/admin/pic"
    }
  },
  methods: {
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePreview(file) {
      // 此处的 file 是整个文件
      // console.log(file.response)
    },
    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${
          files.length + fileList.length
        } 个文件`
      );
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`);
    },
    handleSuccess(response) {
      console.log("响应为"+response);
      this.url = response;
      this.$emit("onUpload");
      this.$message.warning("上传成功");
    },
    clear() {
      this.$refs.uploadRef.clearFiles();
    },
    beforeAvatarUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 2;
      console.log(file.type)
      if (file.type !== "image/jpeg" && file.type !== "image/png") {
        console.log("图片格式不对");
        this.$message.error("上传图片只能是 JPG | PNG 格式!");
        return false;
      }
      if (!isLt2M) {
        console.log("图片太大了");
        this.$message.error("上传图片大小不能超过 2MB!");
        return false;
      }
      return true;
    },
  },
};
</script>

<style lang="less" scoped>
.img-upload {
  height: 100px;
}
</style>

